package vn.edu.ptithcm.pim.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.service.TaskService;
import vn.edu.ptithcm.pim.util.FileUtil;
import vn.edu.ptithcm.pim.util.ParamUtil;

public class ServletServer extends HttpServlet {

	private static final long serialVersionUID = 1L;

	Logger log = Logger.getLogger(ServletServer.class);

	protected void processRequest(HttpServletRequest req,
			HttpServletResponse res) throws ServletException, IOException {
		java.io.PrintWriter out = res.getWriter();
		String type = ParamUtil.getString(req, "type", "");
		log.info("ServletServer || processRequest || type = " + type);
		try {
			if (type.equals(Constants.DELETE_TASK)) {
				long taskId = ParamUtil.getLong(req, "taskId", 0);
				ApplicationContext context = new ClassPathXmlApplicationContext(
						"applicationContext.xml");
				TaskService taskService = (TaskService) context
						.getBean("taskService");
				if (taskService != null) {
					taskService.deleteById(taskId);
				}
				if (taskService.findById(taskId) == null) {
					out.print(Constants.OK_MESSAGE);
				} else {
					out.print(Constants.ERROR_MESSAGE);
				}
			} else if (type.equals(Constants.UPLOAD_FILES)) {
				log.info("upload file || start");
				String pathToFile = FileUtil.transferTo(req,
						Constants.UPLOADED_FILE_FOLDER);
				log.info("upload file || done");
				log.info("path to file : " + pathToFile);
				out.print(pathToFile);
			}
		} catch (Exception e) {
			log.info(e);
			out.print("error");
		} finally {
			out.close();
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
